//
//  DeviceDetailFeature2Cell.m
//  DYLYJ
//
//  Created by JM on 15/11/13.
//  Copyright © 2015年 JM. All rights reserved.
//

#import "DeviceDetailFeature2Cell.h"
#import "DYAudioPlay.h"
#import "YYCategories.h"
#import "Masonry.h"
@interface DeviceDetailFeature2Cell()
@property (nonatomic) CGFloat startBottom;
@property (nonatomic) CGFloat endBottom;
@property (nonatomic) CGFloat offsetY;//定值
@property (nonatomic) CGFloat currentPercent;//当前百分比
@property(nonatomic, strong) NSTimer *timer;
@property(nonatomic, strong) UIView *bottomBar;//操作杆
@property(nonatomic, assign) BOOL isAnimaling;//正在移动中
@end

@implementation DeviceDetailFeature2Cell

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

+ (NSString *)xib {
    return @"DeviceDetailFeature2Cell";
}
+ (NSString *)ID {
    return @"DeviceDetailFeature2Cell";
}
+ (instancetype)cell {
    NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:[DeviceDetailFeature2Cell xib] owner:nil options:nil] ;
    DeviceDetailFeature2Cell * cell = [nibs firstObject];
    cell.backgroundColor = [UIColor clearColor];
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.tintColor = [UIColor clearColor];
    
    //因为动画不是用约束做的，所以这个label会有影响，所以 暂时放到cell上
    cell.perfentLabel.centerX = cell.centerX;
    cell.perfentLabel.centerY = cell.height-30;
    [cell addSubview:cell.perfentLabel];
    [cell.perfentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(cell);
        make.bottom.equalTo(cell).with.offset(-30);
        make.width.equalTo(cell);
        make.height.mas_equalTo(21);
    }];
    
    [cell buildView];
    return cell;
}
- (CGFloat)height {
    return self.frame.size.height;
}
- (void)setDevice:(Device *)device; {
    _device = device;
//    self.upButton.selected = _device.isClose_On;
//    self.downButton.selected = _device.isOpen_On;
//    self.stopButton.selected = _device.isStop_On;
    self.lightButton.selected = _device.isLED_On;
    self.dryButton.selected = _device.isHonggan_On;
    self.airDryButton.selected = _device.isFenggan_On;
    self.xiaoduButton.selected = _device.isXiaodu_On;
    
//    if (self.device.isStop_On){
//        self.perfentLabel.text = @"停";
//    }else if (self.device.isOpen_On){
//        self.perfentLabel.text = @"开";
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self moveOffset:1 withDuration:1 animated:NO];
//        });
//       
//    }else if (self.device.isClose_On){
//        self.perfentLabel.text = @"关";
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self moveOffset:0 withDuration:1 animated:NO];
//        });
//    }
}
#pragma mark- 点击 滑动等事件
//**
- (IBAction)clickStop:(UIButton *)sender {
     _device.isStop_On = YES;
}

- (IBAction)clickLight:(UIButton *)sender {
//    sender.selected = !sender.selected;
//      _device.isLED_On = sender.selected;
    [[DYAudioPlay sharedDYAudioPlay] playOtherSound];
    if ([self.delegate respondsToSelector:@selector(didDeviceClickCmd:)]){
        [self.delegate didDeviceClickCmd:DevieClickCmdLight];
    }
}

- (IBAction)clickDry:(UIButton *)sender {
//    sender.selected = !sender.selected;
//     _device.isHonggan_On = sender.selected;
     [[DYAudioPlay sharedDYAudioPlay] playOtherSound];
    if ([self.delegate respondsToSelector:@selector(didDeviceClickCmd:)]){
        [self.delegate didDeviceClickCmd:DevieClickCmdHongGan];
    }
}
- (IBAction)clickAirDry:(UIButton *)sender {
//    sender.selected = !sender.selected;
//     _device.isFenggan_On = sender.selected;
    [[DYAudioPlay sharedDYAudioPlay] playOtherSound];
    if ([self.delegate respondsToSelector:@selector(didDeviceClickCmd:)]){
        [self.delegate didDeviceClickCmd:DevieClickCmdFengGan];
    }
}
- (IBAction)clickDisinfection:(UIButton *)sender {
//    sender.selected = !sender.selected;
//     _device.isXiaodu_On = sender.selected;
    [[DYAudioPlay sharedDYAudioPlay] playOtherSound];
    if ([self.delegate respondsToSelector:@selector(didDeviceClickCmd:)]){
        [self.delegate didDeviceClickCmd:DevieClickCmdXD];
    }
}
- (IBAction)swipeUp:(id)sender {
//    self.perfentLabel.text = @"ddd";
    NSLog(@"!!!!!!%f",self.viewBottom.bottom);
    [self moveOffset:1 withDuration:4 animated:YES];
//    _device.isClose_On = NO;
//    _device.isOpen_On = YES;
//    _device.isStop_On = NO;
    [[DYAudioPlay sharedDYAudioPlay] playUpDownStop];
    if ([self.delegate respondsToSelector:@selector(didDeviceClickCmd:)]){
        [self.delegate didDeviceClickCmd:DevieClickCmdUp];
    }
}

- (IBAction)swipeDown:(id)sender {
    [self moveOffset:0 withDuration:4 animated:YES];
//    _device.isClose_On = YES;
//    _device.isOpen_On = NO;
//    _device.isStop_On = NO;
   [[DYAudioPlay sharedDYAudioPlay] playUpDownStop];
    if ([self.delegate respondsToSelector:@selector(didDeviceClickCmd:)]){
        [self.delegate didDeviceClickCmd:DevieClickCmdDown];
    }
}

//
#pragma mark -动画相关

// move动画
- (void)moveOffset:(CGFloat) offset withDuration:(CGFloat)duration animated:(BOOL)animated {
    self.viewBottom.alpha = 1.f;
    if (animated == YES) {
        
        [UIView animateWithDuration:8*fabs(self.currentPercent - offset)  delay:0 usingSpringWithDamping:5 initialSpringVelocity:0.2 options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionCurveEaseOut animations:^{
            [self percent:offset];
            [self.timer invalidate];
            self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(updateoffsetY:) userInfo:nil repeats:YES];
            self.isAnimaling = YES;
        } completion:^(BOOL finished) {
            self.isAnimaling = NO;
        }];
        
//        [UIView animateWithDuration:duration*fabs(self.currentPercent - offset) usingSpringWithDamping:0 initialSpringVelocity:0  delay:0 options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionCurveEaseOut animations:^{
//            [self percent:offset];
//            [self.timer invalidate];
//            self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(updateoffsetY:) userInfo:nil repeats:YES];
//             self.isAnimaling = YES;
//            
//        } completion:^(BOOL finished) {
//            self.isAnimaling = NO;
//        }];
    } else {
        [self percent:offset];
        
        NSInteger currentPercent = offset*100;
        if (self.device.isStop_On){
            self.perfentLabel.text = @"停";
        }else if (self.device.isOpen_On){
            self.perfentLabel.text = @"开";
        }else if (self.device.isClose_On){
            self.perfentLabel.text = @"关";
        }
        //self.perfentLabel.text = [NSString stringWithFormat:@"%ld%%",(100-currentPercent)];
    }
}

- (void)updateoffsetY:(id) sender{
    //    if (!self.viewBottom.layer.presentationLayer)
    //        return;
    //    CGFloat xChange = [self.viewBottom.layer.presentationLayer frame].origin.x - self.viewBottom.layer.frame.origin.x;
    CGFloat yChange = [self.viewBottom.layer.presentationLayer frame].origin.y - self.viewBottom.layer.frame.origin.y;;
    CGFloat percent =  yChange/(self.startBottom -self.endBottom);
    if (self.endBottom == self.viewBottom.bottom) {//目标是顶部状态
        percent =  1-percent;
    } else {
        percent =  -percent;
    }
    self.currentPercent = percent;
//
    NSInteger currentPercent = self.currentPercent*100;
    if (self.device.isStop_On){
        self.perfentLabel.text = @"停";
    }else if (self.device.isOpen_On){
        self.perfentLabel.text = @"开";
    }else if (self.device.isClose_On){
        self.perfentLabel.text = @"关";
    }
//    self.perfentLabel.text = [NSString stringWithFormat:@"%ld%%",100-currentPercent];
//
//    NSLog(@"percent:%f",percent);
    CGRect rrr = [self.viewBottom.layer convertRect:[self.viewBottom.layer.presentationLayer frame] toLayer:self.layer.superlayer];
//      NSLog(@"ybottomInMoving:%f,ybottom:%f",CGRectGetMinY([self.viewBottom.layer.presentationLayer frame]),CGRectGetMinY(self.viewBottom.layer.frame));
    if (self.currentPercent == 1||self.currentPercent == 0) {
        [self.timer invalidate];
        self.timer = nil;
    }
    
}

// 配置view
- (void)buildView {
    NSLog(@"viewBottom:%f,viewTop:%f",self.viewBottom.bottom,self.viewTop.bottom);
    CGFloat bottomBarHeight = self.viewBottom.height - self.bottomBar.top;//
    self.startBottom = 435;//self.viewBottom.bottom ;
    self.endBottom = 135+290-156+10;//self.viewTop.bottom+bottomBarHeight;
    self.offsetY = self.endBottom - self.startBottom;
//    self.perfentLabel.text = @"100%";
    if (self.device.isStop_On){
        self.perfentLabel.text = @"停";
    }else if (self.device.isOpen_On){
        self.perfentLabel.text = @"开";
    }else if (self.device.isClose_On){
        self.perfentLabel.text = @"关";
    }
}


// 动画百分比（手动设置动画的程度）
- (void)percent:(CGFloat)percent {
    CGFloat tmpOffsetY = 0;
    
    if (percent <= 0) {
        tmpOffsetY = 0;
    } else if (percent >= 1) {
        tmpOffsetY = self.offsetY;
    } else {
        tmpOffsetY = percent * self.offsetY;
    }
    
    self.viewBottom.bottom = self.startBottom + tmpOffsetY;
    NSLog(@"修改位置为:%f",self.viewBottom.bottom);
}

#pragma mark -动画进行中 点击暂停
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"点击");
    UITouch *t = [touches anyObject];
    CGPoint location = [t locationInView:self.viewBottom];
    CGFloat xChange = [self.viewBottom.layer.presentationLayer frame].origin.x - self.viewBottom.layer.frame.origin.x;
    CGFloat yChange = [self.viewBottom.layer.presentationLayer frame].origin.y - self.viewBottom.layer.frame.origin.y;;
    CGRect rc = [self.viewBottom.layer convertRect:self.viewBottom.layer.bounds toLayer:self.viewBottom.layer];
    rc.origin.x += xChange;
    rc.origin.y += yChange;
    NSLog(@"%@,point:%@",NSStringFromCGRect(rc),NSStringFromCGPoint(location));
     location.x = self.viewBottom.center.x;
    if (CGRectContainsPoint(rc, location)&&self.isAnimaling) {
        
//        _device.isStop_On = YES;
        NSLog(@"击中");
        [[DYAudioPlay sharedDYAudioPlay] playUpDownStop];
        [self.viewBottom.layer removeAllAnimations];
        CGFloat yChange =  CGRectGetMinY([self.viewBottom.layer.presentationLayer frame])- (145);//范围－21到145 iphone6 TODO
        CGFloat percent =  yChange/(self.startBottom -self.endBottom);
        if (self.endBottom == self.viewBottom.bottom) {//目标是顶部状态
            percent =  -percent;
        } else {
            percent =  -percent;
        }
        NSLog(@"currentPercent:%f",percent);
        self.currentPercent = percent;
        [self moveOffset:self.currentPercent withDuration:0.2 animated:NO];
        [self.timer invalidate];//解决停止后 百分比为0的情况
        
        if ([self.delegate respondsToSelector:@selector(didDeviceClickCmd:)]){
            [self.delegate didDeviceClickCmd:DevieClickCmdStop];
        }

    }

}

- (void)didReceiveMessage:(id)message withtype:(NSString *)aSMSType {
    Device *source = message;
    if ([_device.macAddress isEqualToString:source.macAddress]){
        [self setDevice:source];
    }
}

@end
